package huizhi.net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 *
 2、客户端上传一个花桶编号，服务端响应花桶中的花卉代码
 */
public class ServerDatabase1 {
    public static void main(String[] args) throws Exception{
        System.out.println("服务端启动");
        // 启动服务端，监听8888端口
        ServerSocket server = new ServerSocket(8880);
        // 服务端待命，等待客户端连接。在套接字连接之前，都处于阻塞状态
        Socket accept = server.accept();

        // 获取客户端输入字节流
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
        System.out.println("客户端传入：");
        String clientMsg = bufferedReader.readLine();
        System.out.println(clientMsg);

        String sql = "SELECT bis_flower_sku.sku_code FROM bis_bucket JOIN bis_bucket_bunch_map ON bis_bucket.id = bis_bucket_bunch_map.bucket_id" +
                " JOIN bis_flower_bunch_item ON bis_bucket_bunch_map.bunch_id = bis_flower_bunch_item.id " +
                "JOIN bis_flower_sku ON bis_flower_bunch_item.sku_id =  bis_flower_sku.id WHERE bis_bucket.unique_code = ?;";
        Connection connection = ConnectionRequest.requestConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,clientMsg);
        ResultSet resultSet = preparedStatement.executeQuery();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));

        while (resultSet.next()){
            String string = resultSet.getString(1);
            System.out.println("服务端传出：");
            System.out.println(string);
            bufferedWriter.write(string);
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }
        bufferedWriter.close();
        bufferedReader.close();
        accept.close();
        server.close();


    }
}
